<template>
  <div id="footer" class="footer" @touchstart.stop>
    <div class="footer-container">
      <div 
        :ref="(el) => { if (el) store.inputRef = el as HTMLDivElement }" 
        contenteditable 
        class="editable-input"
        data-placeholder="请输入内容"
        @focus="handleFocus"
        @blur="handleBlur"
        @input="handleInput"
        @keydown.enter.prevent="handleSend"
      ></div>
    </div>
    <img class="img" src="@/assets/发送.png" alt="test" @click="handleSend" />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useMobileFooterFixed } from '@/hooks/useMobileFooterFixed'
import { useTestH5Store } from '@/stores/testH5'

const emit = defineEmits<{
  send: [value: string]
}>()

const store = useTestH5Store()
const { inputRef } = storeToRefs(store)
const inputValue = ref('')

// 获取键盘状态和事件处理函数
const { handleFocus, handleBlur, isKeyboardVisible } = useMobileFooterFixed()

// 处理输入内容变化
const handleInput = (e: Event) => {
  const target = e.target as HTMLDivElement
  inputValue.value = target.textContent || ''
}

// 同步 inputValue 到可编辑 div
watch(inputValue, (newValue) => {
  if (inputRef.value && inputRef.value.textContent !== newValue) {
    inputRef.value.textContent = newValue
  }
})

const handleSend = () => {
  const text = inputValue.value.trim()
  if (text) {
    emit('send', text)
    inputValue.value = ''
    
    // 清空可编辑 div
    if (inputRef.value) {
      inputRef.value.textContent = ''
    }
  }
}

</script>

<style scoped lang="scss">
.footer {
  height: 40px;
  background-color: pink;
  flex-shrink: 0;
  display: flex;
  align-items: flex-end;
  padding: 16px 16px env(safe-area-inset-bottom);
  box-sizing: border-box;
  touch-action: none;

  .footer-container {
    width: 80%;
    /* height: auto; */
    min-height: 40px;
    background: #2f2f3b;
    border-radius: 10px;
    border: 1px solid rgba(109, 116, 126, 0.4);
    padding: 4px 4px 4px 15px;
    box-sizing: border-box;
    margin: 0 auto;
    display: flex;
    align-items: center;
  }

  .editable-input {
    flex: 1;
    min-height: 32px;
    max-height: 100px;
    overflow-y: auto;
    outline: none;
    word-break: break-word;
    white-space: pre-wrap;
    color: #fff;
    font-size: 14px;
    line-height: 1.5;

    &:empty:before {
      content: attr(data-placeholder);
      color: #999;
    }
  }
  .img{
    height: 40px;
    margin-left: 10px;
    cursor: pointer;
    user-select: none;
  }
}
</style>
